<template>
  <article style="width: 100%; height: 100%; min-width: 700px;">
    <header class="appointment_header">
      <span class="appointment_header_title">
        &nbsp;
        <i class="el-icon-office-building"></i>
        检测预约管理
      </span>
    </header>

    <section class="appointment_main">
      <div class="appointment_main_header">
        <el-button type="primary" size="small" style="float: left;" @click="openLimitAddUI">
          <i class="el-icon-plus"></i>
          新增可预约时段
        </el-button>
        <div class="appointment_main_header_title">查找到{{filteredData.length}}个结果</div>
        <el-link class="appointment_main_header_refresh" :underline="false" type="primary" @click="handleRefresh">
          <i class="el-icon-refresh"></i>
          刷新
        </el-link>
        <el-input class="appointment_main_header_search" v-model="search" placeholder="输入时间进行搜索" @keyup.enter.native="doFilter">
          <el-link style="padding-right: 5px;" slot="suffix" :underline="false" @click="doFilter">
            <i class="el-icon-search"></i>
            搜索
          </el-link>
        </el-input>
      </div>

      <!-- 信息表格 -->
      <div class="appointment_main_main"> 
        <el-table
          v-loading="loading"
          :header-cell-style="{background: '#ECF1FE'}"
          :data="filteredData.slice((currentPage -1) * pageSize, currentPage * pageSize)"
          min-height="500px"
          :default-sort = "{prop: 'date', order: 'descending'}"
          highlight-current-row
          border
          stripe
        >
          <el-table-column label="检测日期" prop="date"> </el-table-column>
          <el-table-column label="开始时间" prop="startTime"> </el-table-column>
          <el-table-column label="结束时间" prop="endTime"> </el-table-column>
          <el-table-column label="最大名额" prop="maxNumber"> </el-table-column>
          <el-table-column label="已预约名额" prop="currentNumber"></el-table-column>
          <el-table-column
            label="操作"
          >
            <template slot-scope="scope">
              <!-- <el-link
                type="primary"
                style="margin-right: 20px;"
                :underline="false"
                @click="openLimitModifyUI(scope.$index, scope.row)"
              >
                编辑
              </el-link> -->
              <el-link
                type="danger"
                :underline="false"
                @click="handleDelete(scope.$index, scope.row)"
                :disabled="scope.row.currentNumber>0"
              >
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页显示  -->
        <el-pagination
          style="float: right; margin-top: 10px"
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="filteredData.length"
          layout="prev, pager, next, jumper"
        />
      </div>
    </section>

    <aside class="appointment_dialog">
      <!-- 新增可预约时间段 -->
      <el-dialog
        title="可检测时段"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
        :append-to-body="true"
      >
        <el-form label-position="right" label-width="80px" :model="editingLimit">
          <el-form-item label="检测日期">
            <el-date-picker
              v-model="editingLimit.date"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-time-select
              placeholder="起始时间"
              v-model="editingLimit.startTime"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:30',
              }"
            >
            </el-time-select>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-time-select
              placeholder="结束时间"
              v-model="editingLimit.endTime"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:30',
                minTime: editingLimit.startTime,
              }"
            >
            </el-time-select>
          </el-form-item>
          <el-form-item label="检测名额">
            <el-input-number v-model="editingLimit.maxNumber" :min="editingLimit.currentNumber" :max="1000" label="检测名额"></el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="doeditingLimit">确 定</el-button>
        </span>
      </el-dialog>
    </aside>

  </article>
</template>

<script>
import { getLimits, getHospitals, addLimit, modifyLimit, deleteLimit } from "@/api/reservations";
export default {
  data() {
    return {
      limits: [],
      filteredData: [],
      hospitals: [],
      nowHospital: 1,
      // 
      search: '',
      currentPage: 1,
      pageSize: 9,
      loading: false,
      dialogVisible: false,
      editMode: "add", // "modify"
      editingLimit: {
        aiid: null,
        hospitalId: null,
        date: null,
        startTime: null,
        endTime: null,
        maxNumber: null,
        currentNumber: null
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now();
        },
        shortcuts: [
          {
            text: "明天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
    };
  },
  computed: {
    empty: function () {
      return this.limits.length == 0;
    },
  },
  methods: {
    async initHospitals() {
      this.hospitals = await getHospitals();
    },
    async updateLimits() {
      var data = await getLimits(this.nowHospital); 
      this.limits = data.sort((a, b) => {
        if (a.date < b.date) {
          return 1;
        }
        else return -1;
      })
    },
    openLimitAddUI() {
      this.editingLimit.aiid = null,
      this.editingLimit.hospitalId = this.nowHospital,
      this.editingLimit.currentNumber = 0,
      this.dialogVisible = true;
      this.editMode = "add";
    },
    openLimitModifyUI(index, row) {
      this.editingLimit = row;
      this.dialogVisible = true;
      this.editMode = "modify";
    },
    doeditingLimit() {
      console.log(this.editingLimit);
      if (this.editMode == "add") {
        addLimit(this.editingLimit)
        .then(res=>{
          console.log(res);
          this.updateLimits();
          this.dialogVisible = false;
        })
        .catch(error=>console.log(error))
      }
      if (this.editMode == "modify") {
        modifyLimit(this.editingLimit)
        .then(res=>{
          console.log(res);
          this.updateLimits();
          this.dialogVisible = false;
        })
        .catch(error=>console.log(error))
      }
    },
    handleDelete(index, row) {
      this.$confirm("确认删除？")
      .then((opt)=>{
        console.log("删除", opt, row);
        deleteLimit(row.alid)
        .then(res=>{
          console.log(res);
          this.updateLimits();
        })
      })
      .catch((opt) => {
          console.log("删除", opt);
        });
    },
    handleClose() {
      this.$confirm("确认关闭？")
        .then((opt) => {
          console.log("close", opt);
          this.dialogVisible = false;
        })
        .catch((opt) => {
          console.log("close", opt);
        });
    },
    handlePageChange(val) {
      this.currentPage = val;
    },
    doFilter() {
      this.filteredData = this.limits.filter((item) => {
        return item.date.includes(this.search);
      });
      console.log("doFilter:", this.filteredData);
    },
    async handleRefresh(){
      await this.updateLimits();
      this.doFilter();
    }
  },
  created() {
    getHospitals()
        .then((hospitals) => {
          this.nowHospital = hospitals.find(hospital => hospital.phone == this.$store.state.user.userPhone).hospitalId;
          this.handleRefresh();
        })
  },
};
</script>

<style lang="scss" scoped>
.appointment_header {
  background: #FFFFFF;
  border-bottom: 1px solid #DCDFE6;
  width: calc(100% - 60px);
  height: 50px;
  margin: 0px 30px;

  .appointment_header_title {
    font-weight: bold;
    font-size: 22px;
    line-height: 50px;
    margin-left: 5px;
    border-left: 5px solid #21a6e6;
  }
}

.appointment_main {
  margin: 30px 30px 0px 30px;
  width: calc(100% - 60px);

  .appointment_main_header {
    height: 40px;
    line-height: 40px;
    margin-bottom: 30px;

    .appointment_main_header_title {
      color: #919191;
      float: left;
      font-size: 14px;
      margin-left: 20px;
    }

    .appointment_main_header_refresh {
      float: right;
      margin-left: 20px;
    }

    .appointment_main_header_search {
      float: right;
      width: 260px;
    }
  }
}
</style>

<style lang="scss" scoped>

::v-deep .el-button--primary {
  color: #fff;
  background-color: #4875f6;
  border-color: #4875f6;
  -webkit-box-shadow: 0 5px 5px rgba(72,117,246,.15);
  box-shadow: 0 5px 5px rgba(72,117,246,.15);
}

::v-deep .el-button--primary:hover {
  background: #6d91f8;
  border-color: #6d91f8;
  color: #fff;
}

</style>